﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;


namespace TweakSP.Deployment
{
    // http://www.mikhaildikov.com/2007/03/sharepoint-resources-types-use-and_2163.html
    // http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!169.entry
    public class TweakSPInstallationJob : SPJobDefinition
    {
        [Persisted]
        public const string JOB_TITLE = "TweakSP Installation Job";
        [Persisted]
        public const string JOB_NAME = "job-tweaksp-Installation";

        [Persisted]
        private string sourcePath;

        public TweakSPInstallationJob() : base()
        {
        }

        public TweakSPInstallationJob(string jobName, SPWebApplication webApp, string featureName)
            : base(jobName, webApp, null, SPJobLockType.None)
        {
            Debug.WriteLine("TweakSPInstallationJob(" + jobName + ",WebApp(" + webApp.Id + ")," + featureName + ")");
            try
            {
                sourcePath = SPUtility.GetGenericSetupPath("Resources");
                Debug.WriteLine("TweakSPInstallationJob sourcePath: " + sourcePath);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("TweakSPInstallationJob Error: " + ex.ToString());
            }
        }

        public override void Execute(Guid targetInstanceId)
        {
            Debug.WriteLine("TweakSPInstallationJob.Execute");
            try
            {
                SPWebApplication webApp = this.Parent as SPWebApplication;

                foreach (SPUrlZone zone in webApp.IisSettings.Keys)
                {
                    SPIisSettings oSettings = webApp.IisSettings[zone];
                    string destPath = Path.Combine(oSettings.Path.ToString(), "App_GlobalResources");
                    string[] filePaths = Directory.GetFiles(sourcePath, "Tweak*.resx");

                    foreach (string filePath in filePaths)
                    {
                        string fileName = Path.GetFileName(filePath);
                        string dest = Path.Combine(destPath, fileName);
                        Debug.WriteLine("Copying '" + filePath + "' to '" + dest + "'");
                        File.Copy(filePath, dest, true);
                    }
                }

                DeploymentUtilities.CopyAppBinContent();
            }
            catch(Exception ex)
            {
                Debug.WriteLine("Error: " + ex.ToString());
                throw;
            }


        }



    }
}
